package com.lgc.leetcode.easy.addTwoNumbers;

public class Program {
    public static void main(String[] args){
        //[2,4,5]
        ListNode l1 = new ListNode(2);
        ListNode curr2 = new ListNode(4);
        l1.next=curr2;
        ListNode curr3 = new ListNode(5);
        curr2.next=curr3;

        //[5,6,4]
        ListNode l2 = new ListNode(5);
        ListNode currNew2 = new ListNode(6);
        l2.next=currNew2;
        ListNode currNew3 = new ListNode(4);
        currNew2.next=currNew3;

        Program question=new Program();
        question.addTwoNumbers(l1,l2);

        int over=1;
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummyHead = new ListNode(0);
        ListNode p = l1, q = l2, curr = dummyHead;
        int carry = 0;
        while (p != null || q != null) {
            int x = (p != null) ? p.val : 0;
            int y = (q != null) ? q.val : 0;
            int sum = carry + x + y;
            carry = sum / 10;
            curr.next = new ListNode(sum % 10);
            curr = curr.next;
            if (p != null){
                p = p.next;
            }
            if (q != null){
                q = q.next;
            }
        }
        if (carry > 0) {
            curr.next = new ListNode(carry);
        }
        return dummyHead.next;
    }
}
